package com.atzly.community.controller;

import com.atzly.community.constant.CommentConstant;
import com.atzly.community.service.UserService;
import com.atzly.community.utils.CommunityUtils;
import com.atzly.community.utils.RedisKeyUtils;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zlysimida
 * @date 2021/8/25 - 18:42
 */
@Controller
public class LoginController {

    @Autowired
    private Producer producer;

    @Autowired
    private UserService userService;

    @Value("${server.servlet.context-path}")
    private String contentPath;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/login")
    public String loginPage() {
        return "/site/login";
    }


    @PostMapping("/login")
    public String login(String username,
                        String password,
                        String code
                        /** , HttpSession session **/,
                        @CookieValue("kaptchaSuffix") String kaptchaSuffix,
                        HttpServletResponse response,
                        Model model,
                        boolean rememberIs) {

        // 检查验证码
        //String kaptcha = (String) session.getAttribute("kaptcha");
        // 从redis中获取验证码
        String kaptcha = null;
        if (StringUtils.isNotBlank(kaptchaSuffix)) {
            String kaptchaKey = RedisKeyUtils.getKaptchaKey(kaptchaSuffix);
            kaptcha = (String) redisTemplate.opsForValue().get(kaptchaKey);
        }


        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)) {
            model.addAttribute("codeMsg", "验证码不正确!");
            return "/site/login";
        }

        // 检查账号,密码
        int expiredSeconds = rememberIs ? CommentConstant.REMEMBER_EXPIRED_SECONDS : CommentConstant.DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        if (map.containsKey("ticket")) {
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setPath(contentPath);
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);
            return "redirect:/index";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "/site/login";
        }
    }

    @GetMapping("/logout")
    public String logout(@CookieValue("ticket") String ticket) {
        userService.logout(ticket);
        // 退出也需要清除用户的认证信息
        SecurityContextHolder.clearContext();
        return "redirect:/login";
    }

    /**
     * 生成验证码并保存到session中
     * 2 使用redis重构验证功能
     *
     * @param response
     * @param
     */
    @GetMapping("/login/kaptcha")
    public void kaptcha(HttpServletResponse response/**, HttpSession session **/) {
        // 生成验证码
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);

        // 将图片数据存入session
        // session.setAttribute("kaptcha",text);
        // 使用redis存储验证码
        String suffix = CommunityUtils.randomString();
        String kaptchaKey = RedisKeyUtils.getKaptchaKey(suffix);
        Cookie cookie = new Cookie("kaptchaSuffix", suffix);
        cookie.setMaxAge(60);
        cookie.setPath(contentPath);
        response.addCookie(cookie);
        redisTemplate.opsForValue().set(kaptchaKey, text, 60, TimeUnit.SECONDS);


        // 将图片输出给浏览器
        response.setContentType("img/png");
        try {
            OutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 自动处理需要处理异常跳转
    @RequestMapping(value = "/error",method = {RequestMethod.POST,RequestMethod.GET})
    public String exceptionPage() {
        return "/error/500";
    }
}
